import { LinkOutlined } from '@ant-design/icons';
import * as icons from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history, Link } from '@umijs/max';
import React from 'react';
import { message } from 'antd';
import type { MenuDataItem } from '@ant-design/pro-components';
import {
  AvatarDropdown,
  AvatarName,
  Footer,
  Question,
  // SelectLang, // 已关闭国际化
} from '@/components';
import { currentUser as queryCurrentUser } from '@/services/ant-design-pro/api';
import defaultSettings from '../config/defaultSettings';
import '@ant-design/v5-patch-for-react-19';

// 类型定义
interface RouteItem {
  path?: string;
  name?: string;
  icon?: string | React.ReactNode;
  routes?: RouteItem[];
  children?: RouteItem[];
  hideInMenu?: boolean;
  redirect?: string;
  component?: string;
  [key: string]: unknown;
}

interface UserInfo {
  name?: string;
  avatar?: string;
  permissions?: string[];
  [key: string]: unknown;
}

interface InitialState {
  currentUser?: UserInfo;
  dynamicRoutes?: RouteItem[];
  fetchUserInfo?: () => Promise<UserInfo | undefined>;
  settings?: Partial<LayoutSettings>;
}

// 环境与路径常量
const isDev = process.env.NODE_ENV === 'development' || process.env.CI;
const loginPath = '/user/login';

// 图标映射函数：将字符串转换为图标组件
const getIcon = (iconName?: string): React.ReactNode => {
  if (!iconName) return undefined;
  
  // 支持直接使用图标名称（如 'DashboardOutlined'）
  const iconsMap = icons as unknown as Record<string, React.ComponentType>;
  const IconComponent = iconsMap[iconName];
  if (IconComponent) {
    return React.createElement(IconComponent);
  }
  
  return undefined;
};

// 处理路由数据格式
const processRoutes = (routes: RouteItem[]): RouteItem[] => {
  return routes.map((route) => {
    const processedRoute = { ...route };
    
    // 将字符串图标转换为 React 组件
    if (route.icon && typeof route.icon === 'string') {
      processedRoute.icon = getIcon(route.icon);
    }
    
    // 递归处理子路由
    const childRoutes = route.routes || route.children;
    if (childRoutes && Array.isArray(childRoutes)) {
      processedRoute.routes = processRoutes(childRoutes);
      delete processedRoute.children;
    }

    return processedRoute;
  });
};

// 初始化状态
export async function getInitialState(): Promise<InitialState> {
  // 用户信息获取
  const fetchUserInfo = async (): Promise<UserInfo | undefined> => {
    try {
      // 使用 Mock API 获取包含权限的用户信息
      const token = localStorage.getItem('token') || 'mock_token_admin';
      const response = await fetch('/api/currentUser', {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
      const result = await response.json();
      console.log('用户信息:', result.data);
      return result.data;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 开发环境不强制跳转登录
      if (!isDev) {
        history.push(loginPath);
      }
      return undefined;
    }
  };

  // 初始路由获取（根据权限）
  const fetchRoutes = async (): Promise<RouteItem[]> => {
    try {
      // 使用新的权限路由 API
      const response = await fetch('/api/routes/permission', {
       
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token') || 'mock_token_admin'}`,
        },
      });
     
        
      const result = await response.json();
        console.log(result,'response');
      const processed = processRoutes(result.data || []);
      console.log('初始化获取的动态路由:', processed);
      return processed;
    } catch (error) {
      console.error('获取动态路由失败:', error);
      message.error('路由加载失败，请刷新页面重试');
      return [];
    }
  };

  // 并行获取用户信息和路由
  const [currentUser, dynamicRoutes] = await Promise.all([
    fetchUserInfo(),
    fetchRoutes()
  ]);

  return {
    currentUser,
    dynamicRoutes,
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}


// 布局配置
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  // 从 initialState 中获取动态路由数据
  const dynamicRoutes = initialState?.dynamicRoutes || [];
  const currentUser = initialState?.currentUser;
  
  // 过滤出需要在菜单中显示的路由，并转换为 MenuDataItem 格式
  const menuData: MenuDataItem[] = dynamicRoutes.map((route): MenuDataItem => ({
    path: route.path,
    name: route.name,
    icon: route.icon,
    children: route.routes?.map((child): MenuDataItem => ({
      path: child.path,
      name: child.name,
      icon: child.icon,
      hideInMenu: child.hideInMenu,
    })),
    hideInMenu: route.hideInMenu,
  })).filter((route) => !route.hideInMenu);
  
  console.log('✅ 使用后端动态路由数据渲染菜单:', menuData);

  // 页面切换权限校验
  const onPageChange = () => {
    const { location } = history;
    const { currentUser } = initialState || {};

    // 未登录且访问非公共路径时跳转登录
    // if (!currentUser && !publicPaths.includes(location.pathname)) {
    //   history.push(loginPath);
    // }
  };

  return {
    // 右上角操作区
    actionsRender: () => [
      <Question key="doc" />,
      // <SelectLang key="SelectLang" />, // 已关闭国际化
    ],

    // 头像配置
    avatarProps: {
      src: initialState?.currentUser?.avatar || 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
      title: <AvatarName />,
      render: (_, avatarChildren) => <AvatarDropdown>{avatarChildren}</AvatarDropdown>,
    },

    // 水印配置
    waterMarkProps: {
      content: initialState?.currentUser?.name || 'Serati Ma',
    },

    // 页脚渲染
    footerRender: () => <Footer />,

    // 页面切换事件
    onPageChange,

    // 背景图片配置
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],

    // 开发环境链接
    links: isDev
      ? [
        <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
          <LinkOutlined />
          <span>OpenAPI 文档</span>
        </Link>,
      ]
      : [],

    // 禁用默认菜单头部
    menuHeaderRender: undefined,

    // 菜单数据
    menuDataRender: () => menuData,

    // 权限控制
    access: () => ({
      // canAccess: () => !!initialState?.currentUser,
    }),

    // 子组件渲染
    childrenRender: (children) => (
      <>
        {children}
        {isDev && (
          <SettingDrawer
            disableUrlParams
            enableDarkTheme
            settings={initialState?.settings}
            onSettingChange={(settings) => {
              // initialState?.setInitialState?.((prev: any) => ({ ...prev, settings }));
            }}
          />
        )}
      </>
    ),

    // 合并初始设置
    ...initialState?.settings,
  };
};